import tkinter as tk
from tkinter import ttk
import json
from idlelib.colorizer import ColorDelegator
from idlelib.percolator import Percolator

class JsonPage:
    def __init__(self, manager):
        self.manager = manager
        self.root = manager.root
        self.color_delegator = None

    def show(self):
        # 创建主框架
        main_frame = tk.Frame(self.root)
        main_frame.pack(expand=True, fill='both', padx=10, pady=10)

        # 左侧区域
        left_frame = tk.Frame(main_frame)
        left_frame.pack(side='left', expand=True, fill='both')
        
        # 左侧工具栏
        left_toolbar = tk.Frame(left_frame)
        left_toolbar.pack(fill='x')
        tk.Label(left_toolbar, text="输入 JSON:", font=("Arial", 12)).pack(side='left')
        ttk.Button(left_toolbar, text="清空", command=lambda: self.input_text.delete("1.0", tk.END)).pack(side='right', padx=2)
        ttk.Button(left_toolbar, text="复制", command=lambda: self.copy_text(self.input_text)).pack(side='right', padx=2)

        # 左侧文本区域（带行号）
        text_frame = tk.Frame(left_frame)
        text_frame.pack(expand=True, fill='both')
        
        # 行号显示
        self.input_line_numbers = tk.Text(text_frame, width=4, padx=3, takefocus=0, border=0,
                                        background='lightgray', state='disabled')
        self.input_line_numbers.pack(side='left', fill='y')
        
        # 输入文本框
        self.input_text = tk.Text(text_frame, height=20, width=40)
        self.input_text.pack(side='left', expand=True, fill='both')
        self.input_text.bind('<Key>', lambda e: self.update_line_numbers(self.input_text, self.input_line_numbers))
        self.input_text.bind('<MouseWheel>', lambda e: self.sync_scroll(e, self.input_text, self.input_line_numbers))

        # 中间按钮区
        middle_frame = tk.Frame(main_frame)
        middle_frame.pack(side='left', padx=10)
        ttk.Button(middle_frame, text="格式化 →", command=self.format_json).pack(pady=5)
        ttk.Button(middle_frame, text="返回主页", command=self.manager.show_main_page).pack(pady=5)

        # 右侧区域
        right_frame = tk.Frame(main_frame)
        right_frame.pack(side='left', expand=True, fill='both')
        
        # 右侧工具栏
        right_toolbar = tk.Frame(right_frame)
        right_toolbar.pack(fill='x')
        tk.Label(right_toolbar, text="格式化结果:", font=("Arial", 12)).pack(side='left')
        ttk.Button(right_toolbar, text="清空", command=lambda: self.output_text.delete("1.0", tk.END)).pack(side='right', padx=2)
        ttk.Button(right_toolbar, text="复制", command=lambda: self.copy_text(self.output_text)).pack(side='right', padx=2)

        # 右侧文本区域（带行号）
        output_frame = tk.Frame(right_frame)
        output_frame.pack(expand=True, fill='both')
        
        # 行号显示
        self.output_line_numbers = tk.Text(output_frame, width=4, padx=3, takefocus=0, border=0,
                                         background='lightgray', state='disabled')
        self.output_line_numbers.pack(side='left', fill='y')
        
        # 输出文本框
        self.output_text = tk.Text(output_frame, height=20, width=40)
        self.output_text.pack(side='left', expand=True, fill='both')
        
        # 添加语法高亮
        self.color_delegator = ColorDelegator()
        Percolator(self.output_text).insertfilter(self.color_delegator)
        
        self.output_text.bind('<Key>', lambda e: self.update_line_numbers(self.output_text, self.output_line_numbers))
        self.output_text.bind('<MouseWheel>', lambda e: self.sync_scroll(e, self.output_text, self.output_line_numbers))

    def copy_text(self, text_widget):
        self.root.clipboard_clear()
        self.root.clipboard_append(text_widget.get("1.0", tk.END).strip())

    def update_line_numbers(self, text_widget, line_numbers):
        # 更新行号
        text_content = text_widget.get("1.0", tk.END)
        line_count = text_content.count('\n') + 1
        line_numbers_content = '\n'.join(str(i).rjust(3) for i in range(1, line_count))
        line_numbers.config(state='normal')
        line_numbers.delete("1.0", tk.END)
        line_numbers.insert("1.0", line_numbers_content)
        line_numbers.config(state='disabled')
        
        # 同步滚动
        text_widget.yview_moveto(0)
        line_numbers.yview_moveto(0)

    def sync_scroll(self, event, text_widget, line_numbers):
        # 同步滚动行号
        line_numbers.yview_moveto(text_widget.yview()[0])

    def format_json(self):
        try:
            input_json = self.input_text.get("1.0", tk.END).strip()
            parsed = json.loads(input_json)
            formatted = json.dumps(parsed, indent=4, ensure_ascii=False)
            self.output_text.delete("1.0", tk.END)
            self.output_text.insert("1.0", formatted)
            self.update_line_numbers(self.output_text, self.output_line_numbers)
            
            # 刷新语法高亮
            self.color_delegator.recolorize()
        except json.JSONDecodeError as e:
            self.output_text.delete("1.0", tk.END)
            self.output_text.insert("1.0", f"JSON 解析错误:\n{str(e)}")
            self.update_line_numbers(self.output_text, self.output_line_numbers)
        except Exception as e:
            self.output_text.delete("1.0", tk.END)
            self.output_text.insert("1.0", f"发生错误:\n{str(e)}")
            self.update_line_numbers(self.output_text, self.output_line_numbers)